package com.weixiaodong.javabasic.Java8提供的函数式编接口.Optional;

import java.util.HashMap;
import java.util.Optional;

class Student {
    String name;
    HashMap<String, Integer> scoreMap;
    public Student(String name) {
        this.name = name;
    }

    public HashMap<String, Integer> getScoreMap() {
        return scoreMap;
    }

    public void setScoreMap(HashMap<String, Integer> scoreMap) {
        this.scoreMap = scoreMap;
    }
}

@SuppressWarnings("all")
public class OptionalDemo {

    // 冗余的if判断
    public static Integer getScore1(Student student, String subject) {
        if (student != null) {
            if (student.getScoreMap() != null) {
                if (!student.getScoreMap().containsKey(subject)) {
                    return student.getScoreMap().get(subject);
                }
            }
        }
        return null;
    }

    // 使用Optional
    public static Integer getScore2(Student student, String subject) {
        return Optional.ofNullable(student).map(Student::getScoreMap).orElse(null).get(subject);
    }

    public static void main(String[] args) {
        // Optional可以帮助我们更加优雅的判断元素是否为null类型
        // 我们将自己的数据交给Optional管理
    }
}
